import { create } from 'zustand';
import storageService from '../services/storage/storageService';
import planService from '../services/planService';
import { migrateAllData } from '../services/storage/dataMigration';
import { DEFAULT_SETTINGS, STORAGE_KEYS } from '../utils/constants';

/**
 * 计划状态管理 Store (使用 Zustand)
 */
const usePlanStore = create(
    (set, get) => ({
      // 状态
      plans: [],
      weeklyPlans: [],
      monthlyPlans: [],
      settings: DEFAULT_SETTINGS,
      statistics: null,
      isLoading: false,
      error: null,

      // Actions - 计划操作
      addPlan: (planData) => {
        const newPlan = planService.createDailyPlan(planData);
        set((state) => ({
          plans: [...state.plans, newPlan],
        }));
        // 异步保存到存储
        get().savePlans();
        return newPlan;
      },

      updatePlan: (planId, updates) => {
        set((state) => ({
          plans: state.plans.map((plan) =>
            plan.id === planId ? { ...plan, ...updates } : plan
          ),
        }));
        get().savePlans();
      },

      deletePlan: (planId) => {
        set((state) => ({
          plans: state.plans.filter((plan) => plan.id !== planId),
        }));
        get().savePlans();
      },

      togglePlanStatus: (planId) => {
        const plan = get().plans.find((p) => p.id === planId);
        if (plan) {
          const newStatus = plan.status === 'completed' ? 'pending' : 'completed';
          const updatedPlan = planService.updatePlanStatus(plan, newStatus);
          get().updatePlan(planId, updatedPlan);
        }
      },

      // Actions - 周计划操作
      addWeeklyPlan: (weeklyData) => {
        const newWeeklyPlan = planService.createWeeklyPlan(weeklyData);
        set((state) => ({
          weeklyPlans: [...state.weeklyPlans, newWeeklyPlan],
        }));
        get().saveWeeklyPlans();
        return newWeeklyPlan;
      },

      updateWeeklyPlan: (planId, updates) => {
        set((state) => {
          const updatedPlans = state.weeklyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = { ...plan, ...updates };
              // 自动更新完成率
              return planService.updateWeeklyPlanCompletion(updated);
            }
            return plan;
          });
          return { weeklyPlans: updatedPlans };
        });
        get().saveWeeklyPlans();
      },

      deleteWeeklyPlan: (planId) => {
        set((state) => ({
          weeklyPlans: state.weeklyPlans.filter((plan) => plan.id !== planId),
        }));
        get().saveWeeklyPlans();
      },

      // 周计划子任务操作
      addWeeklySubTask: (planId, taskData) => {
        const newTask = planService.createSubTask({
          ...taskData,
          parentId: planId,
        });
        set((state) => {
          const updatedPlans = state.weeklyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = {
                ...plan,
                tasks: [...(plan.tasks || []), newTask],
              };
              return planService.updateWeeklyPlanCompletion(updated);
            }
            return plan;
          });
          return { weeklyPlans: updatedPlans };
        });
        get().saveWeeklyPlans();
        return newTask;
      },

      updateWeeklySubTask: (planId, taskId, updates) => {
        set((state) => {
          const updatedPlans = state.weeklyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = {
                ...plan,
                tasks: (plan.tasks || []).map((task) =>
                  task.id === taskId ? { ...task, ...updates } : task
                ),
              };
              return planService.updateWeeklyPlanCompletion(updated);
            }
            return plan;
          });
          return { weeklyPlans: updatedPlans };
        });
        get().saveWeeklyPlans();
      },

      toggleWeeklySubTask: (planId, taskId) => {
        set((state) => {
          const updatedPlans = state.weeklyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = {
                ...plan,
                tasks: (plan.tasks || []).map((task) => {
                  if (task.id === taskId) {
                    const newStatus = task.status === 'completed' ? 'pending' : 'completed';
                    return {
                      ...task,
                      status: newStatus,
                      completedAt: newStatus === 'completed' ? new Date().toISOString() : null,
                    };
                  }
                  return task;
                }),
              };
              return planService.updateWeeklyPlanCompletion(updated);
            }
            return plan;
          });
          return { weeklyPlans: updatedPlans };
        });
        get().saveWeeklyPlans();
      },

      deleteWeeklySubTask: (planId, taskId) => {
        set((state) => {
          const updatedPlans = state.weeklyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = {
                ...plan,
                tasks: (plan.tasks || []).filter((task) => task.id !== taskId),
              };
              return planService.updateWeeklyPlanCompletion(updated);
            }
            return plan;
          });
          return { weeklyPlans: updatedPlans };
        });
        get().saveWeeklyPlans();
      },

      // Actions - 月计划操作
      addMonthlyPlan: (monthlyData) => {
        const newMonthlyPlan = planService.createMonthlyPlan(monthlyData);
        set((state) => ({
          monthlyPlans: [...state.monthlyPlans, newMonthlyPlan],
        }));
        get().saveMonthlyPlans();
        return newMonthlyPlan;
      },

      updateMonthlyPlan: (planId, updates) => {
        set((state) => {
          const updatedPlans = state.monthlyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = { ...plan, ...updates };
              // 自动更新完成率
              return planService.updateMonthlyPlanCompletion(updated);
            }
            return plan;
          });
          return { monthlyPlans: updatedPlans };
        });
        get().saveMonthlyPlans();
      },

      deleteMonthlyPlan: (planId) => {
        set((state) => ({
          monthlyPlans: state.monthlyPlans.filter((plan) => plan.id !== planId),
        }));
        get().saveMonthlyPlans();
      },

      // 月计划子任务操作
      addMonthlySubTask: (planId, taskData) => {
        const newTask = planService.createSubTask({
          ...taskData,
          parentId: planId,
        });
        set((state) => {
          const updatedPlans = state.monthlyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = {
                ...plan,
                tasks: [...(plan.tasks || []), newTask],
              };
              return planService.updateMonthlyPlanCompletion(updated);
            }
            return plan;
          });
          return { monthlyPlans: updatedPlans };
        });
        get().saveMonthlyPlans();
        return newTask;
      },

      updateMonthlySubTask: (planId, taskId, updates) => {
        set((state) => {
          const updatedPlans = state.monthlyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = {
                ...plan,
                tasks: (plan.tasks || []).map((task) =>
                  task.id === taskId ? { ...task, ...updates } : task
                ),
              };
              return planService.updateMonthlyPlanCompletion(updated);
            }
            return plan;
          });
          return { monthlyPlans: updatedPlans };
        });
        get().saveMonthlyPlans();
      },

      toggleMonthlySubTask: (planId, taskId) => {
        set((state) => {
          const updatedPlans = state.monthlyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = {
                ...plan,
                tasks: (plan.tasks || []).map((task) => {
                  if (task.id === taskId) {
                    const newStatus = task.status === 'completed' ? 'pending' : 'completed';
                    return {
                      ...task,
                      status: newStatus,
                      completedAt: newStatus === 'completed' ? new Date().toISOString() : null,
                    };
                  }
                  return task;
                }),
              };
              return planService.updateMonthlyPlanCompletion(updated);
            }
            return plan;
          });
          return { monthlyPlans: updatedPlans };
        });
        get().saveMonthlyPlans();
      },

      deleteMonthlySubTask: (planId, taskId) => {
        set((state) => {
          const updatedPlans = state.monthlyPlans.map((plan) => {
            if (plan.id === planId) {
              const updated = {
                ...plan,
                tasks: (plan.tasks || []).filter((task) => task.id !== taskId),
              };
              return planService.updateMonthlyPlanCompletion(updated);
            }
            return plan;
          });
          return { monthlyPlans: updatedPlans };
        });
        get().saveMonthlyPlans();
      },

      // Actions - 设置操作
      updateSettings: (newSettings) => {
        set((state) => ({
          settings: { ...state.settings, ...newSettings },
        }));
        get().saveSettings();
      },

      // Actions - 数据加载和保存
      loadAllData: async () => {
        set({ isLoading: true, error: null });
        try {
          // 检查并执行年度清理（1月1日）
          const { checkAndPerformAnnualCleanup } = require('../services/storage/dataMigration');
          const cleanupPerformed = await checkAndPerformAnnualCleanup();
          
          // 如果执行了清理，重新加载数据
          if (cleanupPerformed) {
            set({
              plans: [],
              weeklyPlans: [],
              monthlyPlans: [],
              isLoading: false,
            });
            return;
          }
          
          const [plansResult, weeklyResult, monthlyResult, settingsResult] = await Promise.all([
            storageService.loadPlans(),
            storageService.loadWeeklyPlans(),
            storageService.loadMonthlyPlans(),
            storageService.loadSettings(),
          ]);

          const settings = settingsResult.data || DEFAULT_SETTINGS;
          
          // 执行数据迁移（如果启用自动迁移）
          const migratedData = migrateAllData(
            {
              plans: plansResult.data || [],
              weeklyPlans: weeklyResult.data || [],
              monthlyPlans: monthlyResult.data || [],
            },
            settings
          );

          set({
            plans: migratedData.plans,
            weeklyPlans: migratedData.weeklyPlans,
            monthlyPlans: migratedData.monthlyPlans,
            settings: settings,
            isLoading: false,
          });

          // 如果数据被迁移，保存迁移后的数据
          if (migratedData.plans.length !== (plansResult.data || []).length ||
              migratedData.weeklyPlans.length !== (weeklyResult.data || []).length ||
              migratedData.monthlyPlans.length !== (monthlyResult.data || []).length) {
            get().savePlans();
            get().saveWeeklyPlans();
            get().saveMonthlyPlans();
          }
        } catch (error) {
          set({ error: error.message, isLoading: false });
        }
      },

      savePlans: async () => {
        const { plans } = get();
        await storageService.savePlans(plans);
      },

      saveWeeklyPlans: async () => {
        const { weeklyPlans } = get();
        await storageService.saveWeeklyPlans(weeklyPlans);
      },

      saveMonthlyPlans: async () => {
        const { monthlyPlans } = get();
        await storageService.saveMonthlyPlans(monthlyPlans);
      },

      saveSettings: async () => {
        const { settings } = get();
        await storageService.saveSettings(settings);
      },

      // 清理所有数据
      clearAllData: async () => {
        try {
          // 清空所有计划数据
          set({
            plans: [],
            weeklyPlans: [],
            monthlyPlans: [],
          });
          
          // 清空存储
          await storageService.remove(STORAGE_KEYS.PLANS);
          await storageService.remove(STORAGE_KEYS.WEEKLY_PLANS);
          await storageService.remove(STORAGE_KEYS.MONTHLY_PLANS);
          await storageService.remove(STORAGE_KEYS.STATISTICS);
          
          // 保留设置，只清理计划数据
          return { success: true };
        } catch (error) {
          console.error('Clear data error:', error);
          return { success: false, error: error.message };
        }
      },

      // Actions - 数据筛选和查询
      getPlansByDate: (date) => {
        return get().plans.filter((plan) => plan.scheduledFor === date);
      },

      getPlansByType: (type) => {
        return get().plans.filter((plan) => plan.type === type);
      },

      getPlansByStatus: (status) => {
        return get().plans.filter((plan) => plan.status === status);
      },
    })
);

export default usePlanStore;

